﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// DataGrid 中 图片展示
    /// </summary>
    /// 创建时间：2023-1-5 16:01:35。作者：王浩力
    public class ImgShowConvert : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string imgSaveUrl = System.Convert.ToString(value);
            if (string.IsNullOrWhiteSpace(imgSaveUrl)) return null;
            try
            {
                imgSaveUrl = imgSaveUrl.TrimStart('\\');
                imgSaveUrl = imgSaveUrl.TrimStart('/');

                string imgPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, imgSaveUrl);
                if (!System.IO.File.Exists(imgPath))
                {
                    return null;
                }

                //开始加载图像
                BitmapImage bim = new BitmapImage();
                bim.BeginInit();
                bim.CacheOption = BitmapCacheOption.OnLoad;                 
                bim.StreamSource = System.IO.File.OpenRead(imgPath);
                bim.EndInit();
                return bim;
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog(ex.Message, null, "img_show_error");
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
}
